package org.light4admin.modules.system.controller;

import org.light4admin.common.base.BaseController;
import org.light4admin.common.aop.auth.PreAuthorize;
import org.light4admin.common.base.PageResponse;
import org.light4admin.common.base.Response;
import org.light4admin.modules.system.domain.SysDictData;
import org.light4admin.modules.system.service.ISysDictDataService;
import org.light4admin.modules.system.service.ISysDictTypeService;
import org.light4admin.modules.system.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据字典信息
 *
 * @author light4admin
 */
@RestController
@RequestMapping("/dict/data")
public class SysDictDataController extends BaseController {
    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    @PreAuthorize(hasPermi = "system:dict:list")
    @GetMapping("/list")
    public PageResponse list(SysDictData dictData) {
        startPage();
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        return getDataTable(list);
    }

    /**
     * 查询字典数据详细
     */
    @PreAuthorize(hasPermi = "system:dict:query")
    @GetMapping(value = "/{dictCode}")
    public Response<SysDictData> getInfo(@PathVariable Long dictCode) {
        return Response.success(dictDataService.selectDictDataById(dictCode));
    }

    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/type/{dictType}")
    public Response<List<SysDictData>> dictType(@PathVariable String dictType) {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (CollectionUtils.isEmpty(data)) {
            data = new ArrayList<SysDictData>();
        }
        return Response.success(data);
    }

    /**
     * 新增字典类型
     */
    @PreAuthorize(hasPermi = "system:dict:add")
    @PostMapping
    public Response<Void> add(@Validated @RequestBody SysDictData dict) {
        dict.setCreateBy(SecurityUtils.getUsername());
        dictDataService.insertDictData(dict);
        return Response.success();
    }

    /**
     * 修改保存字典类型
     */
    @PreAuthorize(hasPermi = "system:dict:edit")
    @PutMapping
    public Response<Void> edit(@Validated @RequestBody SysDictData dict) {
        dict.setUpdateBy(SecurityUtils.getUsername());
        dictDataService.updateDictData(dict);
        return Response.success();
    }

    /**
     * 删除字典类型
     */
    @PreAuthorize(hasPermi = "system:dict:remove")
    @DeleteMapping("/{dictCodes}")
    public Response<Void> remove(@PathVariable Long[] dictCodes) {
        dictDataService.deleteDictDataByIds(dictCodes);
        return Response.success();
    }

}
